package circle;

public class CircleDeque<E> {
	private int size;
	private E[] elements;
	private int front;

	@SuppressWarnings("unchecked")

	public CircleDeque() {
		elements = (E[]) new Object[10];
	}

	private int index(int index) {
		int newIndex;
		index += this.front;
		if (index < 0) {
			newIndex = index + elements.length;
		} else {
			newIndex = index - (index >= size ? size : 0);
		}
		return newIndex;
	}

	public int size() {
		return size;
	}

	public boolean isEmpty() {
		return size == 0;
	}

	public void enQueueFront(E element) {
		ensureCapacity(size + 1);
		this.front = index(-1);
		elements[this.front] = element;
		size++;
	}

	public E deQueueFront() { // 不变
		E e = elements[front];
		elements[front] = null;
		front = index(1);
		size--;
		return e;
	}

	public void enQueueRear(E element) { // 不变
		ensureCapacity(size + 1);
		elements[index(0)] = element;
		size++;
	}

	public E deQueueRear() {
		int rearIndex = index(size - 1);
		E e = elements[rearIndex];
		elements[rearIndex] = null;
		size--;
		return e;
	}

	public E front() {
		return elements[front];
	}

	public E Rear() {
		return elements[index(front + size - 1)];
	}

	@SuppressWarnings("unchecked")
	private void ensureCapacity(int capacity) {
		int oldCapacity = elements.length;
		if (oldCapacity < capacity) {
			int newCapacity = oldCapacity + (oldCapacity >> 1);

			E[] newElements = (E[]) new Object[newCapacity];
			for (int i = 0; i < size; i++) {
				newElements[i] = elements[i];
			}
			elements = newElements;
			this.front = 0;
			System.out.print(oldCapacity + "======  kuorongwei: " + newCapacity + "\n");
		}
	}

	public void clear() {
		size = 0;
		for (int i = 0; i < elements.length; i++) {
			elements[i] = null;
		}
		front = 0;
	}
}
